#!/usr/bin/env python3
# coding: utf-8
# Author: Shieber
# Date: 2019.07.24
# transfer docx/doc to pdf
# -a option means transfer all docx/doc files in the current directory to pdf.
#

import sys,time
from os.path import basename, dirname
from subprocess import call

def trans2pdf():
    argv = sys.argv
    if len(sys.argv) < 2:
        script = basename(argv[0])
        print(f'Usage: {script} name.docx or {script} -a')
        sys.exit(-1)

    start = time.time()
    if '-a' == argv[1] or '--all' == argv[1]:
        op1 = 'libreoffice --invisible --convert-to pdf *.doc 1>/dev/null 2>&1'
        op2 = 'libreoffice --invisible --convert-to pdf *.docx 1>/dev/null 2>&1'
        call(op1,shell=True)
        call(op2,shell=True)
    else:
        for fl in argv[1:]:
            if not fl.endswith('.doc') and not fl.endswith('.docx'):
                print('Error, file type does not match!')
                continue

            outdir = dirname(fl) + '/'
            if outdir == '/' or outdir == './/':
                outdir = './'

            op=f'libreoffice --invisible --convert-to pdf {fl} --outdir {outdir} 1>/dev/null 2>&1'
            call(op,shell=True)

    durateion = time.time() - start
    print(f'耗时：{durateion:.2f}(s)')

if __name__ == '__main__':
    trans2pdf()
